use std::thread;

use cs2s::command::{CommandQueueClientHandle, TerminateStatus};
use signal_hook::iterator::SignalsInfo;

/// Handle signals to terminate the server.
pub(crate) fn handle(command_queue: impl Into<String>, mut signals: SignalsInfo) {
    let command_queue = command_queue.into();

    thread::spawn(move || {
        while let Some(signal) = signals.forever().next() {
            warn!("received signal: {}, terminating...", signal);
            if let Err(err) =
                CommandQueueClientHandle::terminate(&command_queue, TerminateStatus::Success)
            {
                error!("failed to terminate: {}", err);
            } else {
                break;
            }
        }
    });
}
